<?php
/**
 * 1.读取配置，2自动加载，3请求分发
 * User: Traun
 * Date: 2021/8/21
 * Time: 15:16
 * @copyright Copyright (c) 湖南悦奥网络技术有限公司 .
 */

class Base
{
    public function run(){
        $this->loadConfig();
        $this->registerAutoload();
        $this->getRequestParams();
        $this->dispatch();
    }
    // 加载配置
    private function loadConfig(){
        $GLOBALS['config'] = require './app/config/config.php';
    }

    // 用户自定义类的加载方法
    public function userAutoLoad($className){
        // 定义基本类的列表
        $baseClass = [
            'Model' => './framework/Model.php',
            'Db' => './framework/Db.php',
        ];
        if (isset($baseClass[$className])) {
            require $baseClass[$className];//加载基类
        } elseif (substr($className,-5) == 'Model') {
            require './app/index/model/'.$className.'.php';// 加载用户自定义模型
        } elseif (substr($className,-10) == 'Controller') {
            require './app/index/controller/'.$className.'.php';//加载用户自定义控制器
        }
    }
    // 注册自动加载
    private function registerAutoload(){
        spl_autoload_register([$this,'userAutoLoad']);
    }
    // 获取请求参数
    private function getRequestParams(){
        //模块
        $defPlate = $GLOBALS['config']['app']['default_platform'];
        $p = isset($_GET['p']) ? $_GET['p'] : $defPlate;
        define('PLATFORM',$p);

        // 控制器
        $defController = $GLOBALS['config'][PLATFORM]['default_controller'];
        $c = isset($_GET['c']) ? $_GET['c'] : $defController;
        define('CONTROLLER',$c);

        // 控制器
        $defAction = $GLOBALS['config'][PLATFORM]['default_action'];
        $a = isset($_GET['a']) ? $_GET['a'] : $defAction;
        define('ACTION',$a);
    }
    // 请求分发
    private function dispatch(){
        $controllerName = CONTROLLER.'Controller';
        $controller = new $controllerName;

        $actionName = ACTION;
        $controller->$actionName();
    }
}